/**
 * 
 */
package com.airnews.ticket.ui.order;

import java.util.Calendar;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import com.airnews.ticket.R;
import com.airnews.ticket.model.OrderInfoResult;
import com.airnews.ticket.model.SearchOrder;
import com.airnews.ticket.net.WebAccessor;
import com.airnews.ticket.ui.BaseActivity;
import com.airnews.ticket.ui.Main;
import com.airnews.ticket.util.AddrUtil;
import com.mobclick.android.MobclickAgent;

/**
 * @author luoxz
 *
 */
public class OrderSearch extends BaseActivity {
	
	private final static int DATE_DIALOG = 0;
	private final static int TIME_DIALOG = 1;
	public final int NORESULT = 3;
	public final int NOORDER = 4;
	public final int NOORDERSTAT = 5;
	public final int NET_ERROR=6;
	public final int SEARCH_ERROR=7;
	public  final int TIME_DIALOG_ID = 8;
	public  final int DIALOG_SINGLE_CHOICE = 9;
	public  final int DIALOG_LIST = 10;
	
	private TextView orderScoll, orderStatus, bookOrderType, orderTimeStart, orderTimeEnd, orderSearchButton, passagerName, orderNo, ticketNo;
	
	String[] selectOptionList=null;
	
	private Calendar c = null;
	
	private ProgressDialog progressDialog = null;
	public Handler myHandler;
	
	AddrUtil addrUtil;
	
    private SharedPreferences sp;
	private String loginNameRe = "";
	private String isLoninOK = null;//是否登录
	private String autoLogin = null;//记着登录
	private Button backBut;
	private Toast toast;
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.order_search);
		
		activityList.add(this);  
		
		addrUtil = new AddrUtil(this);
		
		orderNo = (TextView)findViewById(R.id.orderNo);
		passagerName = (TextView)findViewById(R.id.passagerName);
		
		orderScoll = (TextView)findViewById(R.id.orderScoll);
		orderScoll.setOnClickListener(clickListener);
		
		orderStatus = (TextView)findViewById(R.id.orderStatus);
		orderStatus.setOnClickListener(clickListener);
		
		bookOrderType = (TextView)findViewById(R.id.bookOrderType);
		bookOrderType.setOnClickListener(clickListener);
		
		orderTimeStart = (TextView)findViewById(R.id.orderTimeStart);
		orderTimeStart.setOnClickListener(clickListener);
		
		orderTimeEnd = (TextView)findViewById(R.id.orderTimeEnd);
		orderTimeEnd.setOnClickListener(clickListener);
		
		orderSearchButton = (TextView)findViewById(R.id.orderSearchButton);
		orderSearchButton.setOnClickListener(clickListener);
		
		sp = getSharedPreferences("UserInfoB2C", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
		initConfig();
		
		backBut = (Button) findViewById(R.id.backBut);
		backBut.setOnClickListener(clickListener);
		
		myHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case NORESULT:
					toast = Toast.makeText(OrderSearch.this, "未找到符合条件的航班", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case NOORDER:
					toast = Toast.makeText(OrderSearch.this, "无订单信息", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case NOORDERSTAT:
					toast = Toast.makeText(OrderSearch.this, "订单信息未获得更新", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case NET_ERROR:
					toast = Toast.makeText(OrderSearch.this, "网络超时，连接失败", Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				case SEARCH_ERROR:
					toast = Toast.makeText(OrderSearch.this, (String)msg.obj, Toast.LENGTH_LONG);
					toast.setGravity(Gravity.CENTER, 0, 0);
					toast.show();
					break;
				}
				super.handleMessage(msg);
			}
		};
	}
	
	OnClickListener clickListener= new OnClickListener() { 
    	public void onClick(View v) { 
    		switch (v.getId()) {
    		case R.id.orderScoll: {//订单范围
    			selectOptionList=new String[]{"全部机票","国内机票","国际机票"};
    	          new AlertDialog.Builder(OrderSearch.this)
    	            .setTitle("选择")
    	            .setItems(
    	            		selectOptionList,
    	            		new DialogInterface.OnClickListener() {
		    	              public void onClick(DialogInterface dialog, int whichcountry) {                                      
		    	            	  orderScoll.setText(selectOptionList[whichcountry]);
		    	              }
		    	            })
    	            .setNegativeButton(
    	            		"取消", 
    	            		new DialogInterface.OnClickListener() { 
		    	              public void onClick(DialogInterface d, int which) { 
		    	                d.dismiss(); 
		    	              }
		    	            })
    	            .show();
    	          break;
    			}
    		case R.id.orderStatus: {//订单状态
    			selectOptionList=new String[]{"全部订单","未提交","未处理","处理状态","成交","取消","全部退票","部分退票"};
    	          new AlertDialog.Builder(OrderSearch.this)
    	            .setTitle("选择")
    	            .setItems(
    	            		selectOptionList,
    	            		new DialogInterface.OnClickListener() {
    	    	              public void onClick(DialogInterface dialog, int whichcountry) {                                      
    	    	            	  orderStatus.setText(selectOptionList[whichcountry]);
    	    	              }
    	    	            })
    	            .setNegativeButton(
    	            		"取消", 
    	            		new DialogInterface.OnClickListener() { 
    	    	              public void onClick(DialogInterface d, int which) { 
    	    	                d.dismiss(); 
    	    	              }
    	    	            })
    	            .show();
    	          break;
    			}
    		case R.id.bookOrderType: {//预定方式
    			selectOptionList=new String[]{"全部订单","网上预订","电话订单"};
    	          new AlertDialog.Builder(OrderSearch.this)
    	            .setTitle("选择")
    	            .setItems(
    	            		selectOptionList,
    	            		new DialogInterface.OnClickListener() {
    	    	              public void onClick(DialogInterface dialog, int whichcountry) {                                      
    	    	            	  bookOrderType.setText(selectOptionList[whichcountry]);
    	    	              }
    	    	            })
    	            .setNegativeButton(
    	            		"取消", 
    	            		new DialogInterface.OnClickListener() { 
    	    	              public void onClick(DialogInterface d, int which) { 
    	    	                d.dismiss(); 
    	    	              }
    	    	            })
    	            .show();
    	          break;
    		}
    		case R.id.orderTimeStart: {//选择开始日期
    			showDialog(R.id.orderTimeStart);
    	        break;
    		}
    		case R.id.orderTimeEnd: {//选择结束日期
  			  showDialog(R.id.orderTimeEnd);
  	          break;
  			}
    		case R.id.orderSearchButton: {//订单查询
    			search();
    	         break;
    			}
    		case R.id.backBut:
    			Intent intentR = new Intent();
    			intentR.setClass(OrderSearch.this, Main.class);
    			Bundle bundleR=new  Bundle();
    			bundleR.putString("loginName", loginNameRe);
    			bundleR.putString("isLoninOK", isLoninOK);
    			bundleR.putString("autoLogin", autoLogin);
    			sp.edit().putString("loginName",loginNameRe).commit();
    			sp.edit().putString("isLoninOK",isLoninOK).commit();
    			sp.edit().putString("isAutoLogin",autoLogin).commit();
    			intentR.putExtras(bundleR);
    			setResult(RESULT_OK, intentR);
    			finish();
				break;
    		}
    	}
	};
	
    //初始化配置
    private void initConfig() {
     loginNameRe = sp.getString("loginName", "");
     isLoninOK = sp.getString("isLoninOK", null);
     autoLogin = sp.getString("isAutoLogin", null);
    }
    
	/**
     * 创建日期选择对话框
     */
    @Override
	protected Dialog onCreateDialog(final int id) {
		Dialog dialog = null;
		c = Calendar.getInstance();
		dialog = new DatePickerDialog(this,
				new DatePickerDialog.OnDateSetListener() {
					public void onDateSet(DatePicker dp, int year, int month,
							int dayOfMonth) {
						if (R.id.orderTimeStart == id) {
							orderTimeStart.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
						} else if (R.id.orderTimeEnd == id) {
							orderTimeEnd.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
						}
					}
				}, c.get(Calendar.YEAR), // 传入年份
				c.get(Calendar.MONTH), // 传入月份
				c.get(Calendar.DAY_OF_MONTH) // 传入天数
		);

		return dialog;
	}	
    
    private void search() {
    	final String ticketNoValue = "";
    	final String orderNoValue = orderNo.getText().toString();
    	final String passagerNameValue = passagerName.getText().toString();
		final String orderScollValue = orderScoll.getText().toString();
		final String orderStatusValue = orderStatus.getText().toString();
		final String bookOrderTypeValue = bookOrderType.getText().toString();
		final String orderTimeStartValue = orderTimeStart.getText().toString();
		final String orderTimeEndValue = orderTimeEnd.getText().toString();
		
		ContentValues values = new ContentValues();
		values.put("orderNo", orderNoValue);
		values.put("orderScoll", orderScollValue);
		values.put("orderStatus", orderStatusValue);
		values.put("bookOrderType", bookOrderTypeValue);
		values.put("orderTimeStart", orderTimeStartValue);
		values.put("orderTimeEnd", orderTimeEndValue);
		values.put("ticketNo", ticketNoValue);
		//HistoryDB.insert(OrderSearch.this, values);
		progressDialog = ProgressDialog.show(this, "请稍等...", "查询订单中...",true);
		final Thread thread1 = new Thread() {
			public void run() {
				SearchOrder searchOrder = new SearchOrder();
				searchOrder.TicketNo = ticketNoValue;
				searchOrder.OrderStatus = orderStatusValue;
				searchOrder.PassagerName = passagerNameValue;
				searchOrder.OrderNo = orderNoValue;
				searchOrder.StartOrderTime = orderTimeStartValue;
				searchOrder.EndOrderTime = orderTimeEndValue;
				//searchFlight.fclassGrade = fclassGrade;
				
		        String userIdLogin = sp.getString("userId", null);
		        Log.i("OrderSearch userIdLogin", userIdLogin);
		        String userPwd =  sp.getString("userPwd", null);
		        Log.i("OrderSearch userPwd", userPwd);
		        
				OrderInfoResult orderInfoResult =  WebAccessor.searchOrderInfo(OrderSearch.this, searchOrder,userIdLogin,userPwd);
				
				if (progressDialog.isShowing()) {
					if (orderInfoResult== null) {
						Message msg = new Message();
						msg.what = NORESULT;
						myHandler.sendMessage(msg);
					}else if(!"0".equals(orderInfoResult.Ret_Code)){
						Message msg = new Message();
						msg.what = SEARCH_ERROR;
						msg.obj = orderInfoResult.Ret_Msg;
						myHandler.sendMessage(msg);
					}else{
						Intent intent3 = new Intent();
						intent3.setClass(OrderSearch.this, OrderList.class);
						intent3.putExtra("searchOrder", searchOrder);
						intent3.putExtra("orderScoll", orderScollValue);
						intent3.putExtra("orderStatus",orderStatusValue);
						intent3.putExtra("bookOrderType", bookOrderTypeValue);
						intent3.putExtra("orderTimeStart", orderTimeStartValue);
						intent3.putExtra("orderTimeEnd", orderTimeEndValue);
						OrderList.orderist = orderInfoResult.OrderInfos;
						OrderList.searchOrder = searchOrder;
						Log.i("OrderList", String.valueOf(orderInfoResult.OrderInfos.size()));
						startActivity(intent3);
						overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
					}
					progressDialog.dismiss();
				}
			}
		};
		progressDialog.setCancelable(true);
		thread1.start();
	}
	
	public void onResume() {     
		super.onResume();     
		MobclickAgent.onResume(this); 
	}  
	
	public void onPause() {     
		super.onPause();     
		MobclickAgent.onPause(this); 
	}  
}
